import { SettingsService } from '@delon/theme';
import { Component, OnDestroy, Inject, Optional, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import {
  SocialService,
  TokenService,
  DA_SERVICE_TOKEN,
} from '@delon/auth';
import { ReuseTabService } from '@delon/abc';
import { StartupService } from '@core/startup/startup.service';
import { CacheService } from '@core/routes-services/cache.service';
import { LoginService } from '@core/routes-services/login.service';
import { CurrUserService } from '@core/routes-services/Observer-service/curr-user.service';
import { CurrUserModel } from '@core/routes-services/Observer-service/curr-user.model';

@Component({
  selector: 'passport-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less'],
  providers: [SocialService],
})
export class UserLoginComponent implements OnInit, OnDestroy {
  form: FormGroup;
  error = '';
  type = 0;
  loading = false;
  currUser: CurrUserModel = new CurrUserModel(null, null, null);

  constructor(
    fb: FormBuilder,
    private router: Router,
    public msg: NzMessageService,
    private modalSrv: NzModalService,
    private settingsService: SettingsService,
    private socialService: SocialService,
    @Optional()
    @Inject(ReuseTabService)
    private reuseTabService: ReuseTabService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: TokenService,
    private startupSrv: StartupService,
    private cacheService: CacheService,
    private loginService: LoginService,
    private currUserService: CurrUserService,
  ) {
    this.form = fb.group({
      userName: [null, [Validators.required, Validators.minLength(3)]],
      password: [null, Validators.required],
      mobile: [null, [Validators.required, Validators.pattern(/^1\d{10}$/)]],
      captcha: [null, [Validators.required]],
      remember: [true],
    });
    modalSrv.closeAll();
  }

  ngOnInit(): void {
    // 到登录页自动退出 清空缓存
    if (this.cacheService.getTokenInfo()) {
      this.loginService.logout();
    }
    this.currUserService.currUserChange.subscribe((currUserModel) => {
      this.currUser = currUserModel;
    });
  }

  // region: fields

  get userName() {
    return this.form.controls.userName;
  }

  get password() {
    return this.form.controls.password;
  }

  get mobile() {
    return this.form.controls.mobile;
  }

  get captcha() {
    return this.form.controls.captcha;
  }

  // endregion

  switch(ret: any) {
    this.type = ret.index;
  }

  // region: get captcha

  count = 0;
  interval$: any;

  getCaptcha() {
    this.count = 59;
    this.interval$ = setInterval(() => {
      this.count -= 1;
      if (this.count <= 0) clearInterval(this.interval$);
    }, 1000);
  }

  // endregion

  submit() {
    this.error = '';
    if (this.type === 0) {
      this.userName.markAsDirty();
      this.userName.updateValueAndValidity();
      this.password.markAsDirty();
      this.password.updateValueAndValidity();
      if (this.userName.invalid || this.password.invalid) return;
    } else {
      this.mobile.markAsDirty();
      this.mobile.updateValueAndValidity();
      this.captcha.markAsDirty();
      this.captcha.updateValueAndValidity();
      if (this.mobile.invalid || this.captcha.invalid) return;
    }
    this.loading = true;
    this.loginService.login({ 'name': this.userName.value, 'password': this.password.value }).then((res) => {
      let authToken = res.headers.get('Authorization');
      this.cacheService.setTokenInfo(authToken);
      let id = res.body.data.id;
      let name = res.body.data.username;
      let role = res.body.data.role;
      let currUser = new CurrUserModel(id, name, role);
      this.currUserService.setCurrUser(currUser);
      this.cacheService.setCurrUserInfo(currUser);
      this.router.navigate(['/']);
      this.loading = false;
    }, (error) => {// 后台验证错误再根据具体错误指定 control dialog
      this.loading = false;
      if (error.status == 401) {
        this.error = '用户名或密码错误';
      } else {
        this.msg.error(error.message ? error.message : error.error);
      }
    });
  }


  // endregion

  ngOnDestroy(): void {
    if (this.interval$) clearInterval(this.interval$);
  }

}
